package com.yoyo.itravel.web.filter;

import com.yoyo.itravel.constants.UserConstant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Description 非法访问后台过滤器（未登录）
 *
 * @author HZX
 * @date 2020/5/9 14:54
 */
@WebFilter("/admin/*")
public class IllegalAccessAdminFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 转换
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;

        if (!request.getRequestURI().contains("admin/login.jsp")) {
            // 获得Session对象
            HttpSession session = request.getSession();
            // 获得session中的管理员对象
            Object obj = session.getAttribute(UserConstant.ADMIN);

            // 判断用户是否登录
            if (obj == null) { // 未登录
                // 跳转登录界面
                response.sendRedirect(request.getContextPath() + "/admin/login.jsp");
            }
        }

        // 已登录或访问登录界面，直接放行
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
